package org.igeek.atomqq.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;

import org.igeek.atomqq.widget.BadgeView;

import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.View.OnKeyListener;

/** 
 * 小工具
 * @author <a href="http://hangxin1940.cnblogs.com">hangxin1940@gmail.com</a>
 * @time 2012-2-2 上午11:45:17 
 */
public class Utils {
	private static String PATH_FRIEND_FACE="/userface";
	private static String PATH_GROUP_FACE="/groupface";
	private static String PATH_ATOM="/AtomQQ";
	
	/**
	 * 存储用户头像
	 * @param uin 当前登录用户
	 * @param friend 好友
	 * @param img 输入流
	 * @throws IOException
	 */
	public static String writeFriendFaceImage(long uin,long friend,InputStream img) throws IOException{
		
		String fileName=Environment.getExternalStorageDirectory().toString();
		
		//是否是登录账户头像
		if(uin==friend)
			fileName+=PATH_ATOM+"/"+uin+"/"+uin;
		else
			fileName+=PATH_ATOM+"/"+uin+PATH_FRIEND_FACE+"/"+friend;
			
		
		File file=new File(fileName);
		
		if(!file.getParentFile().exists()) 
			file.getParentFile().mkdirs(); 
		
		FileOutputStream fw=new FileOutputStream(file);
		
		int ch=0;
		while((ch=img.read()) != -1){  
			fw.write(ch);
		}
		fw.close();
		
		
		return fileName;
	}
	
	public static String writeGroupFaceImage(long uin,long gid,InputStream img) throws IOException{
		
		String fileName=Environment.getExternalStorageDirectory().toString();
		
		fileName+=PATH_ATOM+"/"+uin+PATH_GROUP_FACE+"/"+gid;
		
		
		File file=new File(fileName);
		
		if(!file.getParentFile().exists()) 
			file.getParentFile().mkdirs(); 
		
		FileOutputStream fw=new FileOutputStream(file);
		
		int ch=0;
		while((ch=img.read()) != -1){  
			fw.write(ch);
		}
		fw.close();
		
		
		return fileName;
	}
	
	/**
	 * 用户头像是否存在
	 * @param uin 当前登录用户
	 * @param friend 好友
	 * @return
	 */
/*	public static boolean hasFriendFace(long uin,long friend){
		String path=Environment.getExternalStorageDirectory().toString();
		
		//是否是登录账户头像
		if(uin==friend)
			path+=PATH_ATOM+"/"+uin+"/"+uin;
		else
			path+=PATH_ATOM+"/"+uin+PATH_FRIEND_FACE+"/"+friend;
		
		
		File file=new File(path);
		if(!file.exists()) 
			return false;
		
		return true;
	}*/
	
	public static String getFriendFacePath(long uin,long faceid){
		String path=Environment.getExternalStorageDirectory().toString();
		
		//是否是登录账户头像
		if(uin==faceid)
			path+=PATH_ATOM+"/"+uin+"/"+uin;
		else
			path+=PATH_ATOM+"/"+uin+PATH_FRIEND_FACE+"/"+faceid;
		
		
		File file=new File(path);
		if(!file.exists()) 
			return "";
		
		return path;
	}
	
	public static String getGroupFacePath(long uin,long gid){
		String path=Environment.getExternalStorageDirectory().toString();
		
		path+=PATH_ATOM+"/"+uin+PATH_GROUP_FACE+"/"+gid;
		
		
		File file=new File(path);
		if(!file.exists()) 
			return "";
		
		return path;
	}
	
	/**
	 * 获取用户头像Drawable
	 * @param uin 当前登录用户
	 * @param friend 好友
	 * @return
	 *//*
	public static Drawable getFriendFaceDrawable(long uin,long friend){
		String path=Environment.getExternalStorageDirectory().toString();
		
		//是否是登录账户头像
		if(uin==friend)
			path+=PATH_ATOM+"/"+uin+"/"+uin;
		else
			path+=PATH_ATOM+"/"+uin+PATH_FRIEND_FACE+"/"+friend;
		
		
		File file=new File(path);
		if(!file.exists()) 
			return null;
		
		return Drawable.createFromPath(path);
	}*/
	
	/**
	 * 获取状态栏高度
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static int getStatusBarHeight(Context context) throws Exception{
		
		if(sbarHeight<=-1){
			//获得标题栏高度
			Class<?> c = Class.forName("com.android.internal.R$dimen");
			Object obj = c.newInstance();
			Field field = c.getField("status_bar_height");
			int x = Integer.parseInt(field.get(obj).toString());
			sbarHeight = context.getResources().getDimensionPixelSize(x);
		}
		
		return sbarHeight;
		
	}
	
	private static int sbarHeight=-1;
	private static int screenHeight=-1;
	private static int screenWidth=-1;
	
	
	/**
	 * 向桌面添加一个窗口
	 * @param callerView
	 * @param targetHeight
	 * @param mAddedView
	 * @param context
	 * @throws Exception
	 */
	public static void showViewOnTopWindow(View callerView ,int targetHeight,final BadgeView mAddedView,Context context) throws Exception{

		if(sbarHeight<=-1||screenHeight<=-1||screenWidth<=-1){
			
			getStatusBarHeight(context);
			
			DisplayMetrics  dm = new DisplayMetrics();
			//取得窗口属性
			((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
	
			//窗口高度
			screenHeight = dm.heightPixels;
			screenWidth = dm.widthPixels;
		}
		
		targetHeight=dip2px(context, targetHeight);
		
		int[] callerLocation={0,0};
		callerView.getLocationOnScreen(callerLocation);
		int callerHeight=callerView.getHeight();
		int callerWidth=callerView.getWidth();
        
        int offsetX=0-screenWidth/2;
        int offsetY=0-screenHeight/2+sbarHeight;
        
        int callerX=callerLocation[0]+offsetX;
        int callerY=callerLocation[1]+offsetY;
        
        int targetX=offsetX;
        int targetY=callerY-targetHeight+callerHeight;
        
        
        int arowX=callerX+(callerWidth/2-mAddedView.getWidth()/2)-offsetX;
        
        if((callerY-offsetY)<targetHeight){
        	targetY+=targetHeight-dip2px(context, 3);
        	mAddedView.setUpArow(arowX);
        }else{
        	targetY-=sbarHeight+dip2px(context, 18);
        	mAddedView.setDownArow(arowX);
        }
        
 
        final WindowManager mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); 

        
        
        mAddedView.setOnKeyListener(new OnKeyListener() { 
             
            public boolean onKey(View v, int keyCode, KeyEvent event) { 
            	mWindowManager.removeView(mAddedView);
            	mAddedView.setOnKeyListener(null);
            	return false; 
            } 
            
           
        }); 
        
        
        mAddedView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction()==MotionEvent.ACTION_DOWN){
					Rect rect=new Rect();
					mAddedView.getHitRect(rect);
					
					
					if(event.getY()<0||event.getY()>rect.bottom){
						mWindowManager.removeView(mAddedView);
		            	mAddedView.setOnTouchListener(null);
					}
				}
				return false;
				
			}

			
			
		});
        
         
        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.x = targetX; 
        params.y = targetY; 
        params.width = screenWidth; 
        params.height = targetHeight; 
        params.format=PixelFormat.RGBA_8888;
        params.packageName = context.getPackageName();
        params.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;  
 
        //贴到透明Activity上 
        
        mWindowManager.addView(mAddedView,params);
	}
	
	/** 
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
     */  
    public static int dip2px(Context context, float dpValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }  
  
    /** 
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
     */  
    public static int px2dip(Context context, float pxValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    }  
}
